// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuex from 'vuex'
import { WechatPlugin } from 'vux'
import FastClick from 'fastclick'
import VueRouter from 'vue-router'
import router from '@/router/index'
import App from '@/App'
import axios from 'axios'
import jssha from 'js-sha1'
import jsmd5 from 'js-md5'
import '@/font-awesome/css/font-awesome.min.css'

Vue.use(Vuex)
Vue.use(WechatPlugin)
Vue.use(VueRouter)
// sha1
Vue.prototype.$jssha = jssha
Vue.prototype.$jsmd5 = jsmd5
// appid
// welink服务器
// const basedomain = 'http://m.lining.meijiewd.com'
// const apidomain = 'http://lining.meijiewd.com'
// 测试服
const basedomain = 'https://liningweixintest.lining.com/front/'
const apidomain = 'https://liningweixintest.lining.com/wechat'
// 正式服
// const basedomain = 'https://weixin.lining.com/front/'
// const apidomain = 'https://weixin.lining.com/wechat'
// welink 平台id
// const componentappid = 'wx6088cabc0a099afc'
// 李宁测试平台id
const componentappid = 'wx49f99d12d48c26d5'
// 李宁平台id
// const componentappid = 'wxf749871bb3fe304b'
Vue.prototype.basedomain = basedomain
Vue.prototype.apidomain = apidomain
Vue.prototype.componentappid = componentappid
Vue.prototype.wxredirectname = ''
sessionStorage.setItem('componentappid', componentappid)
// axios
const newaxios = axios.create({
  // baseURL: 'http://lining.meijiewd.com',
  timeout: 30000,
  withCredentials: true,
  transformRequest: [function (data, headers) {
    return JSON.stringify(data)
  }]
  // auth: {
  //   username: 'kuikui',
  //   password: 'kuikuipwd'
  // }
})
newaxios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// newaxios.interceptors.request.use(function (config) {
//   // 在发送请求之前做些什么
//   console.log(config)
//   return config
// }, function (error) {
//   // 对请求错误做些什么
//   console.log(error)
//   return Promise.reject(error)
// })
// axios.interceptors.response.use(function (response) {
//   // 对响应数据做点什么
//   console.log(response)
//   return response
// }, function (error) {
//   // 对响应错误做点什么
//   console.log(error)
//   return Promise.reject(error)
// })
Vue.prototype.$axios = newaxios
const getArrList = (url, params = {}) => {
  return axios.get(url, {params: params})
  .then(function (response) {
    return response.data
  })
  .catch(function (error) {
    console.log(error)
    return []
  })
}
const getObjDetail = (url, params = {}) => {
  return axios.get(url, {params: params})
  .then(function (response) {
    return response.data
  })
  .catch(function (error) {
    console.log(error)
  })
}
Vue.prototype.getArrList = getArrList
Vue.prototype.getObjDetail = getObjDetail
// cookie
const setCookie = (name, value, day = 7) => {
  const exp = new Date()
  exp.setTime(exp.getTime() + day * 24 * 60 * 60 * 1000)
  document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString()
}
const getCookie = (name) => {
  let arr = []
  const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  if (document.cookie.match(reg)) {
    arr = document.cookie.match(reg)
    return unescape(arr[2])
  } else {
    return null
  }
}
const delCookie = (name) => {
  const exp = new Date()
  exp.setTime(exp.getTime() - 1)
  const cval = getCookie(name)
  if (cval != null) {
    document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
  }
}
Vue.prototype.setCookie = setCookie
Vue.prototype.getCookie = getCookie
Vue.prototype.delCookie = delCookie
// routeto
Vue.prototype.routeto = (str, params) => {
  params = params || {}
  params.appid = getCookie('appid')
  params.wxredirectname = str
  // 强制给index.html 加上时间戳
  if (document.URL.indexOf('t=') < 0) {
    let timestamp = (new Date()).valueOf()
    params.t = timestamp
  }
  str = str || '*'
  router.push({ name: str, query: params })
}

FastClick.attach(document.body)

Vue.config.productionTip = false

const store = new Vuex.Store({})

store.registerModule('vux', {
  state: {
    isLoading: false,
    isShowHomeTip: true // 是否展示个人中心的弹出层
  },
  mutations: {
    updateLoadingStatus (state, payload) {
      state.isLoading = payload.isLoading
    }
  }
})
// wx
const configWxFun = (to) => {
  if (to.meta.needjsapi === 'true') {
    const timestamp = Date.parse(new Date()) / 1000
    const nonceStr = Math.random().toString(36).substr(2)
    const url = window.location.href.split('#')[0]
    getObjDetail(apidomain + '/api/wechat/mp/getJsApiTicket/' + getCookie('appid'))
    .then((data) => {
      const signature = jssha('jsapi_ticket=' + data.data + '&noncestr=' + nonceStr + '&timestamp=' + timestamp + '&url=' + url)
      Vue.wechat.config({
        debug: false,
        appId: getCookie('appid'),
        timestamp: timestamp,
        nonceStr: nonceStr,
        signature: signature,
        jsApiList: [
          'chooseCard',
          'addCard',
          'openCard',
          'scanQRCode',
          'openLocation',
          'getLocation',
          'onMenuShareTimeline',
          'onMenuShareAppMessage'
        ]
      })
    }, () => {})
  }
}
Vue.prototype.configWxFun = configWxFun

router.beforeEach(function (to, from, next) {
  // 强制给index.html 加上时间戳
  if (document.URL.indexOf('t=') < 0) {
    let timestamp = (new Date()).valueOf()
    to.query.t = timestamp
  }
  const appid = getCookie('appid') || ''
  if (to.name === 'routewechatticket') {
    setCookie('appid', to.query.appid)
  } else {
    if (appid !== to.query.appid) {
      delCookie('openid')
      delCookie('islogin')
      delCookie('buycarlist')
      // this.routeto(this.$route.query.wxredirectname)
    }
  }
  if (to.name === 'productlist') {
    switch (to.query.type) {
      case 'all':
        to.meta.title = '所有商品'
        break
      case 'canbeinto':
        to.meta.title = '可兑换商品'
        break
      case 'entity':
        to.meta.title = '实物商品'
        break
      case 'coupon':
        to.meta.title = '优惠券'
        break
      default:
        to.meta.title = '所有商品'
        break
    }
  }
  if (to.name === 'choicenesslist') {
    switch (to.query.type) {
      case '1':
        to.meta.title = '篮球'
        break
      case '2':
        to.meta.title = '综训'
        break
      case '3':
        to.meta.title = '跑步'
        break
      case '4':
        to.meta.title = '时尚'
        break
      default:
        to.meta.title = '篮球'
        break
    }
  }
  document.title = to.meta.title || ''
  if (getCookie('islogin') === 'true') {
    if (to.name === 'wechat') {
      store.commit('updateLoadingStatus', {isLoading: false})
    } else {
      store.commit('updateLoadingStatus', {isLoading: true})
    }
  } else {
    if ((getCookie('islogin') !== 'true') && (to.name !== 'wechat') && (to.name !== 'wechatcode') && (to.name !== 'wechatticket') && (to.name !== 'routewechatticket') && (to.name !== 'notfound') && (to.name !== 'clearcookie')) {
      store.commit('updateLoadingStatus', {isLoading: true})
      router.push({ name: 'wechat', query: {appid: to.query.appid, wxredirectname: to.query.wxredirectname} })
    } else {
      store.commit('updateLoadingStatus', {isLoading: false})
    }
  }
  if (to.name === 'coupleBack') {
    store.commit('updateLoadingStatus', {isLoading: false})
  }
  next()
})

router.afterEach(function (to) {
  // wechat
  configWxFun(to)
  Vue.wechat.error((res) => {
    console.log(res)
  })
  if (window.zhuge) {
    if ((getCookie('islogin') === 'true') && (to.name !== 'wechat') && (to.name !== 'wechatcode') && (to.name !== 'wechatticket') && (to.name !== 'routewechatticket') && (to.name !== 'notfound') && (to.name !== 'clearcookie')) {
      if (!window.iszhugeon) {
        window.zhugeid = getCookie('openid')
        window.zhuge.identify(window.zhugeid)
        window.iszhugeon = true
      }
      window.zhuge.track('页面载入', {
        '目标页面': to.meta.title,
        'OpenID': getCookie('openid'),
        '点击时间': (new Date().toLocaleString())
      })
    }
  }
  setTimeout(() => {
    store.commit('updateLoadingStatus', {isLoading: false})
    document.body.className = ''
  }, 500)
})

/* eslint-disable no-new */
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app-box')
